﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace Common.ECS
{
    public class Entity : IEntity
    {
        public int EntityID
        {
            get;set;
        }

        public Dictionary<ComponentType, IComponent> Components
        {
            get
            {
                return components;
            }
        }
        private Dictionary<ComponentType, IComponent> components =new Dictionary<ComponentType, IComponent>();

        private Dictionary<Type, Dictionary<string, IAdapter>> Adapters = new Dictionary<Type, Dictionary<string, IAdapter>>();

        public virtual void Init()
        {

        }

        public TAdapater GetAdapterByPath<TAdapater>(string path)where TAdapater:IAdapter
        {
            if (components.ContainsKey(ComponentType.GameObjectComponent))
            {
                GameObject go = ((GameObjectComponent)components[ComponentType.GameObjectComponent]).CurGameObject;

                if (Adapters.ContainsKey(typeof(TAdapater)))
                {
                    if (Adapters[typeof(TAdapater)].ContainsKey(path))
                    {
                        return (TAdapater)Adapters[typeof(TAdapater)][path];
                    }
                }
                else
                {

                    Adapters.Add(typeof(TAdapater), new Dictionary<string, IAdapter>());
                    TAdapater[] childAdapters = go.GetComponentsInChildren<TAdapater>();
                    for (int i = 0; i < childAdapters.Length; i++)
                    {
                        Adapters[typeof(TAdapater)].Add(childAdapters[i].GetPathInParent(), childAdapters[i]);
                    }

                    TAdapater[] selfAdapters = go.GetComponentsInChildren<TAdapater>();
                    for (int i = 0; i < childAdapters.Length; i++)
                    {
                        Adapters[typeof(TAdapater)].Add(childAdapters[i].GetPathInParent(), childAdapters[i]);
                    }
                }
                return (TAdapater)Adapters[typeof(TAdapater)][path];
            }

            return default(TAdapater);

        }
    }
}
